package com.comecrd.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
public class WechatUtil {
    
    @Value("${wechat.appId}")
    private String appId;
    
    @Value("${wechat.secret}")
    private String secret;
    
    private final RestTemplate restTemplate = new RestTemplate();
    
    // 微信登录，获取openId和sessionKey
    public Map<String, String> wxLogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={secret}&js_code={code}&grant_type=authorization_code";
        
        Map<String, String> params = new HashMap<>();
        params.put("appId", appId);
        params.put("secret", secret);
        params.put("code", code);
        
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class, params);
        JSONObject result = JSONObject.parseObject(response.getBody());
        
        Map<String, String> loginResult = new HashMap<>();
        
        if (result.containsKey("errcode")) {
            loginResult.put("error", result.getString("errmsg"));
        } else {
            loginResult.put("openId", result.getString("openid"));
            loginResult.put("sessionKey", result.getString("session_key"));
        }
        
        return loginResult;
    }
}